package com.artifact.mit.mypoint.fragment.app;

import static com.artifact.mit.mypoint.service.util.Variable.PREFS_NAME;
import static com.artifact.mit.mypoint.service.util.Variable.SHARED_POINT;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.ContextWrapper;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.artifact.mit.mypoint.R;
import com.artifact.mit.mypoint.activity.MyPointBaseActivity;
import com.artifact.mit.mypoint.service.ServiceHandler;
import com.artifact.mit.mypoint.service.async.ImageLoader;
import com.artifact.mit.mypoint.service.async.NewsAsync;
import com.artifact.mit.mypoint.service.async.PromoAsync;
import com.artifact.mit.mypoint.service.model.SetImage;
import com.artifact.mit.mypoint.service.model.api.Catalogue;
import com.artifact.mit.mypoint.service.model.api.Catalogue.CatalogueDetail;
import com.artifact.mit.mypoint.service.model.api.Point;
import com.artifact.mit.mypoint.service.util.APICall;
import com.artifact.mit.mypoint.service.util.FormatHelper;

public class DashboardFragment extends Fragment {

	private TextView name;
	private TextView memberUserId;
	private TextView point;
	private TextView promoName1;
	private TextView promoName2;
	private TextView promoDesc1;
	private TextView promoDesc2;
	private TextView newsName1;
	private TextView newsName2;
	private TextView newsDesc1;
	private TextView newsDesc2;
	private ImageView promoImage1;
	private ImageView promoImage2;
	private ImageView newsImage1;
	private ImageView newsImage2;
	private ImageView profile;
	private Button btnPromo;
	private Button btnNews;
	
	private View includePromo1;
	private View includePromo2;
	private View includeNews1;
	private View includeNews2;
	
	private ServiceHandler serviceHandler;
	private SharedPreferences preferences;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.dashboard_layout, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		serviceHandler = new ServiceHandler(getActivity());
		
		name = (TextView) getView().findViewById(R.id.name);
		memberUserId = (TextView) getView().findViewById(R.id.id);
		point = (TextView) getView().findViewById(R.id.point);
		profile = (ImageView) getView().findViewById(R.id.profile);
		preferences = getActivity().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
		
		includePromo1 = getView().findViewById(R.id.include1);
		promoName1 = (TextView) includePromo1.findViewById(R.id.textView1);
		promoDesc1 = (TextView) includePromo1.findViewById(R.id.textView2);
		promoImage1 = (ImageView) includePromo1.findViewById(R.id.imageView1);
		
		includePromo2 = getView().findViewById(R.id.include2);
		promoName2 = (TextView) includePromo2.findViewById(R.id.textView1);
		promoDesc2 = (TextView) includePromo2.findViewById(R.id.textView2);
		promoImage2 = (ImageView) includePromo2.findViewById(R.id.imageView1);
		
		includeNews1 = getView().findViewById(R.id.include3);
		newsName1 = (TextView) includeNews1.findViewById(R.id.textView1);
		newsDesc1 = (TextView) includeNews1.findViewById(R.id.textView2);
		newsImage1 = (ImageView) includeNews1.findViewById(R.id.imageView1);
		
		includeNews2 = getView().findViewById(R.id.include4);
		newsName2 = (TextView) includeNews2.findViewById(R.id.textView1);
		newsDesc2 = (TextView) includeNews2.findViewById(R.id.textView2);
		newsImage2 = (ImageView) includeNews2.findViewById(R.id.imageView1);
		
		btnPromo = (Button) getView().findViewById(R.id.btnPromo);
		btnPromo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				FragmentTransaction fragmentTrx = getFragmentManager().beginTransaction();
				PromoFragment promoFragment = new PromoFragment();				
				//fragmentTrx.setCustomAnimations(R.anim.slide_up, R.anim.slide_down);
				fragmentTrx.replace(R.id.main_frame, promoFragment);
				fragmentTrx.commit();
			}
		});
		
		btnNews = (Button) getView().findViewById(R.id.btnNews);
		btnNews.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				FragmentTransaction fragmentTrx = getFragmentManager().beginTransaction();
				NewsFragment newsFragment = new NewsFragment();
				//fragmentTrx.setCustomAnimations(R.anim.slide_up, R.anim.slide_down);
				fragmentTrx.replace(R.id.main_frame, newsFragment);
				fragmentTrx.commit();
			}
		});
		
		new ImageLoader().execute(new SetImage(profile, preferences.getString("image", ""), false));
		
		new PointAsync().execute("");
			
		new PromoAsync(getActivity(), promoName1, promoDesc1, promoImage1, promoName2, promoDesc2, promoImage2, true).execute("");
		
		new NewsAsync(getActivity(), newsName1, newsDesc1, newsImage1, newsName2, newsDesc2, newsImage2, true).execute("");
			
		new MenuAsync().execute("");
		
		name.setText(preferences.getString("name", ""));
		memberUserId.setText(preferences.getString("memberUserId", ""));
		point.setText(preferences.getString("point", ""));
	}
	
	private void setProgress(int visibility){
		MyPointBaseActivity activity = ((MyPointBaseActivity) getActivity());
		if (activity != null)
			activity.setProgressBar(visibility);
	}
	
	private class PointAsync extends AsyncTask<String, Void, Point> {
		
		@Override
		protected void onPreExecute() {
			setProgress(View.VISIBLE);
		}
		
		@Override
		protected void onPostExecute(Point result) {
			if(result != null){
				if(!"".equals(result.getUserPointBook().getSaldo())){
					String pointVal = FormatHelper.formatNumber(result.getUserPointBook().getSaldo()); 							
					point.setText(pointVal);
					serviceHandler.commitEditor(SHARED_POINT, result.getUserPointBook().getSaldo());
					MyPointBaseActivity activity = ((MyPointBaseActivity)getActivity()); 
					if (activity != null)
						((MyPointBaseActivity) getActivity()).setPoint(pointVal);
					setProgress(View.GONE);					
					return;
				}
			}
			point.setText("0");
			setProgress(View.GONE);
			
		}
		
		@Override
		protected Point doInBackground(String... arg0) {
			MyPointBaseActivity activity = ((MyPointBaseActivity)getActivity()); 
			if (activity != null) {
				try {
					return serviceHandler.pointService();
				} catch (Exception e) {
					Log.e(this.getClass().getName(), "Error Point Service", e);
				}
			}
			return null;
		}

	}
	private class MenuAsync extends AsyncTask<String, Void, Map<String, ArrayList<CatalogueDetail>>> {

		@Override
		protected Map<String, ArrayList<CatalogueDetail>> doInBackground(String... arg0) {
			Map<String, ArrayList<CatalogueDetail>> map = new HashMap<String, ArrayList<CatalogueDetail>>();
			Catalogue catalogue = APICall.catalogue(getActivity());
			if (catalogue != null) {
				CatalogueDetail catalogueDetail[] = catalogue.getCatalogueDetails();
				for (int x = 0; x < catalogueDetail.length; x++) {
					if (map.get(catalogueDetail[x].getDpName()) != null) {
						map.get(catalogueDetail[x].getDpName()).add(catalogueDetail[x]);
					} else {
						ArrayList<CatalogueDetail> arrayList = new ArrayList<CatalogueDetail>();
						arrayList.add(catalogueDetail[x]);
						map.put(catalogueDetail[x].getDpName(), arrayList);
					}
				}
				try{
					ContextWrapper cw = new ContextWrapper(getActivity());
					File directory = cw.getDir("dat", Context.MODE_PRIVATE);
					File file = new File(directory, "menu.ser");
					FileOutputStream f = new FileOutputStream(file);
					ObjectOutputStream s = new ObjectOutputStream(f);
					s.writeObject(map);
					s.close();
				}catch(Throwable e){
					e.printStackTrace();
				}
				return map;
			} else {
				return null;
			}
		}
	}
}
